package utl.mofen.dbOperator;

//
//{        
//    "key": 18020303,
//    "step": 1,
//    "trace":true,   //跟踪SQL,
//    "params": 
//     {
//       "$rep_where": " and 1=1"
//     }        
//},

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import utl.mofen.delphi.cds.Util;
import utl.mofen.intf.IDBOperator;
import utl.mofen.script.SQLParser;
import utl.mofen.utils.GsonUtil;
import utl.mofen.utils.StringUtil;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

public class ExecuteScript {
	JsonObject config = null;
	IDBOperator dbOpera = null;
	SQLParser sqlParser = null;
	
	//解析出来的SQL
	String parsedSQL = "";
	
	/**
	 * 解析的SQL语句
	 * @throws Exception 
	 *   找不到解析的SQL语句时可能会抛出一次
	 */
    public void executeParseSQL() throws Exception
    {
		JsonObject script = config;
		String sql = "";
		if (script.has("sql")) {
			sql = script.get("sql").getAsString();
		} else if (script.has("key") && script.has("step")) 
		{
			sqlParser.clear();
			sqlParser.setScriptKey(script.get("key").getAsInt());
			sqlParser.setScriptStep(script.get("step").getAsInt());
			
			JsonElement param = script.get("params");

			if (param != null) {

				Set<Map.Entry<String, JsonElement>> params = param
						.getAsJsonObject().entrySet();
				if (params != null) {

					Iterator<Entry<String, JsonElement>> param_it = params
							.iterator();

					while (param_it.hasNext()) {
						Entry<String, JsonElement> e = param_it.next();

						String p_name = e.getKey();
						sqlParser.setParam(p_name,
								GsonUtil.json2String(e.getValue()));
					}
				}
			}
			sql = sqlParser.getScript();
		}
		this.parsedSQL = sql;
    }
    
    public String getParsedSQL()
    {
    	return parsedSQL;
    }
    
	
	public void setConfig(JsonObject __config)
	{
		this.config = __config;		
	}
	
	public void setDBOpera(IDBOperator __dbOpera)
	{
		this.dbOpera = __dbOpera;		
	}
	
	public void clear()
	{
		this.parsedSQL = "";
		this.sqlParser.clear();
	}
	
	public void setSQLParser(SQLParser __sqlParser)
	{
		this.sqlParser = __sqlParser;	
	}
	
	public String open(boolean raiseIsEmpty) throws Exception
	{
		if (StringUtil.stringIsEmpty(this.parsedSQL))
		{
			this.executeParseSQL();
		}
		return Util.getXMLData(dbOpera.queryData(parsedSQL));
	}
	
	
	public int execute(boolean raiseIsEmpty) throws Exception
	{
		if (StringUtil.stringIsEmpty(this.parsedSQL))
		{
			this.executeParseSQL();
		}
		String sql = parsedSQL;
		if (StringUtil.stringIsNotEmpty(sql))
		{		
//			this.dbOpera.clearBatch();
//			this.dbOpera.addSQL4BatchExecute(sql);
//			this.dbOpera.executeBatchSQL();
			return this.dbOpera.executeSQL(sql);
		}else
		{
			if (raiseIsEmpty)
			{
				throw new Exception("没有指定要执行的SQL语句");
			}
		}
		return -1;
	}
}
